//
//  MNDHistoryDiscountViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/13.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDHistoryDiscountViewController.h"
#import "MNDAlertDiscountReguraViewController.h"
#import "MNDDiscountModel.h"
#import "MNDHistoryDiscountTableViewCell.h"
#import "SYRefreshControl.h"
#import "MNDLoginUserModel.h"
@interface MNDHistoryDiscountViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *historyDiscountTabview;
/* 模型数组 */
@property (strong, nonatomic) NSMutableArray<MNDDiscountModel*> *discountModelArray;
@property (weak, nonatomic) IBOutlet UIView *noneDataView;
@property (nonatomic, assign) NSInteger perpageNum;

@end

@implementation MNDHistoryDiscountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"历史卡券";
    [self setupUI];
    self.historyDiscountTabview.estimatedRowHeight = 44;
    self.historyDiscountTabview.rowHeight = UITableViewAutomaticDimension;
    [self initialBarbuttonItems];
}

- (void)initialBarbuttonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"使用规则"
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(clickUseRegula:)];
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBlack];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[item];
    }
}

//使用规则弹窗
- (IBAction)clickUseRegula:(UIButton *)sender {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDAlertDiscountReguraViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDAlertDiscountReguraViewController"];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
    //    __weak typeof(self) weakSelf = self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (![MNDLoginUserModel isUserLogin]) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
}

- (NSMutableArray<MNDDiscountModel *> *)discountModelArray {
    if (!_discountModelArray) {
        _discountModelArray = [NSMutableArray array];
    }
    return _discountModelArray;
}
#pragma mark -加载数据
- (void)loadData:(BOOL)isPullDown {

    if (isPullDown) {
        if (self.discountModelArray.count <= 0) {
            [self.view beginLoading];
        }
        _perpageNum = 1;
    } else {
        _perpageNum++;
    }
    __weak typeof(self) weakSelf = self;
    NSDictionary *paramsDict = @{@"coupon_status": @"5", @"perpage": @(_perpageNum), @"pagesize": @10};
    
    NSDictionary *params = [MNDSign signedParamWithDict:paramsDict];
    
    [APIManager sendRequestWithPath:API_DISCOUNT_LIST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            NSArray *modelArray = [MNDDiscountModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"coupon_list"]];
            
            if (isPullDown) {
                [weakSelf.view configBlankPage:SYBlankPageTypeNoData hasData:modelArray.count reloadButtonBlock:nil];
                [weakSelf.discountModelArray removeAllObjects];
            }
            [weakSelf.discountModelArray addObjectsFromArray:modelArray];
            NSLog(@"%@",weakSelf.discountModelArray);
            [SYRefreshControl configAfterLoading:weakSelf.historyDiscountTabview hasData:modelArray.count];
        } else {
            [SYRefreshControl configAfterLoading:weakSelf.historyDiscountTabview hasData:YES];
            if (self.discountModelArray.count <= 0) {
                [weakSelf.view configBlankPage:SYBlankPageTypeError hasData:YES reloadButtonBlock:^(id sender) {
                    [weakSelf loadData:isPullDown];
                }];
            }
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        [weakSelf.historyDiscountTabview reloadData];
        
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakSelf.historyDiscountTabview hasData:YES];
        [NetworkProgressHUD showHudNetworkError:error];
        if (weakSelf.discountModelArray.count <= 0) {
            SYBlankPageType blankType = [weakSelf.view blankPageTypeWithError:error];
            [weakSelf.view configBlankPage:blankType hasData:YES reloadButtonBlock:^(id sender) {
                [weakSelf loadData:isPullDown];
            }];
        }
    }];
}

#pragma mark -搭建界面

- (void)setupUI {
    WeakSelf(self);
    
    [SYRefreshControl configGifMJRefresh:self.historyDiscountTabview refreshType:MJRefreshSupportALl beginRefresh:NO timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        [weakself loadData:YES];
    } loadMoreBlock:^{
        [weakself loadData:NO];
    }];
    [self loadData:YES];
}

#pragma mark -UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.discountModelArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    MNDHistoryDiscountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNDHistoryDiscountTableViewCell"];
    MNDDiscountModel *model = self.discountModelArray[indexPath.row];
    if ([model.coupon_explain containsString:@"，"]) {
        cell.titleLabel.text = model.coupon_explain;
        if(kScreenWidth < 375){
            cell.titleLabel.font = [UIFont systemFontOfSize:16];
            
        }else{
            cell.titleLabel.font = [UIFont systemFontOfSize:18];
        }
        
    }else {
        NSMutableAttributedString *titleStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",model.coupon_explain]];
        [titleStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(0, titleStr.length)];
        [titleStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(titleStr.length-3, 3)];
        cell.titleLabel.attributedText = titleStr;
    }
    cell.validdateLabel.text = model.coupon_remake;
    if ([model.coupon_status_name isEqualToString:@"已过期"]) {//已过期
        NSString *dataStr = [NSString stringWithFormat:@"有效期至%@",model.coupon_activation_validdate];
        cell.dateLabel.text = dataStr;
    }else if([model.coupon_status_name isEqualToString:@"已使用"]){//
        NSString *dataStr = [NSString stringWithFormat:@"有效期%@至%@",model.coupon_valid_start_date,model.coupon_valid_end_date];
        cell.dateLabel.text = dataStr;
    }else {//已取消
    
    }
    cell.couponSourceLabel.text = [NSString stringWithFormat:@" %@", model.coupon_source];
    [cell.statusBtn setBackgroundColor:[UIColor whiteColor]];
    cell.statusBtn.layer.borderWidth = 1;
    cell.statusBtn.layer.borderColor = [UIColor colorWithRed:181/255.0 green:181/255.0 blue:181/255.0 alpha:1.0].CGColor;
    [cell.statusBtn setTitleColor:[UIColor colorWithRed:142/255.0 green:142/255.0 blue:142/255.0 alpha:1.0] forState:UIControlStateNormal];
    [cell.statusBtn setTitle:model.coupon_status_name forState:UIControlStateNormal];
    return cell;
}

- (IBAction)useReguarBtn:(UIButton *)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDAlertDiscountReguraViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDAlertDiscountReguraViewController"];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
